﻿using QD.LopPlat.UI.Code;
using QD.SQLHelper;
using QD.Tools;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Sql;
using System.IO;
using System.Net;
using System.ServiceProcess;
using System.Windows.Forms;

namespace QD.LopPlat.UI
{
    public partial class Login : Form
    {
        /// <summary>
        /// 记录所有历史登录的信息文件路径
        /// </summary>
        private string pwdFilePath;


        public Login()
        {
            InitializeComponent();

            this.ControlBox = false;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.FormBorderStyle = FormBorderStyle.FixedSingle; //不可以拖动改变大小

            string rootPath = System.AppDomain.CurrentDomain.BaseDirectory;
            pwdFilePath = Path.Combine(rootPath, "QDDevPlat_V4.txt");

            this.AcceptButton = this.button1;
            this.CancelButton = this.button2;
        }

        private void DataBaseLogin_Load(object sender, EventArgs e)
        {
            Source_DataBindByLocal();
            this.cbsecurity.SelectedIndex = 0;

            AutoUidPwd("");
        }

        //加载本地sql实例
        private void Source_DataBindByLocal()
        {
            string HostName = Dns.GetHostName();
            ServiceController[] services = ServiceController.GetServices();
            List<string> list = new List<string>();

            foreach (ServiceController s in services)
            {
                if (s.ServiceName.ToLower() == "mssqlserver")
                {
                    list.Add(HostName);
                }
                else if (s.ServiceName.ToLower().IndexOf("mssql$") != -1)
                {
                    list.Add(HostName + "\\" + s.ServiceName.Substring(s.ServiceName.IndexOf("$") + 1));
                }
            }

            //加载历史记录
            string pwds = FileHelper.ReadFromTxt(pwdFilePath);
            string[] strs = pwds.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (string str in strs)
            {
                string[] pwd = str.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                if (pwd.Length == 3)
                {
                    if (!list.Contains(pwd[0]))
                    {
                        list.Add(pwd[0]);
                    }
                }
            }

            this.cbSource.DataSource = list;
            this.cbSource.SelectedIndex = this.cbSource.Items.IndexOf(HostName);
        }

        //加载局域网sql实例
        private void Source_DataBindByLAN()
        {
            SqlDataSourceEnumerator SqlDataSourceEnumerator = SqlDataSourceEnumerator.Instance;

            DataTable dt = SqlDataSourceEnumerator.GetDataSources();

            List<string> list = new List<string>();
            foreach (DataRow dr in dt.Rows)
            {
                list.Add(dr["ServerName"].ToString());
            }

            this.cbSource.DataSource = list;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string _cbSource = this.cbSource.Text;
                string _uid = this.txtUID.Text.Trim();
                string _pwd = this.txtPWD.Text.Trim();
                int _logonType = 0;

                if (this.cbsecurity.Text == "SQL Server 身份证验")
                {
                    _logonType = 2;
                }
                else
                {
                    _logonType = 1;
                }

                bool isOk = QDUserHelper.LoginDb(_cbSource, _uid, _pwd, _logonType);

                if (isOk)
                {
                    if (DbConfig.Instance.LogonConfig.LogonType == 2 && this.rembDbMes.Checked)
                    {
                        string str = FileHelper.ReadFromTxt(pwdFilePath);
                        string newpwd = DbConfig.Instance.LogonConfig.ServerName + " " + DbConfig.Instance.LogonConfig.UserID + " " + TextHelper.StringEncoding(DbConfig.Instance.LogonConfig.PassWord);

                        if (str.Contains(newpwd))
                        {
                            //如果存在，则将原记录清除，再将新记录添加到最后面，因为页面初始化时，默认要加载最后一条记录
                            string _newpwd = str.Replace(newpwd + "\r\n", "").Replace(newpwd, "");
                            FileHelper.AddToTxt(pwdFilePath, _newpwd);
                        }

                        FileHelper.AppendToTxt(pwdFilePath, newpwd);
                    }

                    DataBaseSel form2 = new DataBaseSel();
                    this.Hide();
                    form2.Show();
                }
            }
            catch (Exception ex)
            {
                Tools.PromptHelper.Prompt(ex);
            }
        }

        private void rblocal_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rblocal.Checked)
                Source_DataBindByLocal();
        }

        private void rblan_CheckedChanged(object sender, EventArgs e)
        {
            if (this.rblan.Checked)
                Source_DataBindByLAN();
        }

        //身份验证切换
        private void cbsecurity_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cbsecurity.SelectedIndex == 0)
            {
                this.txtUID.Text
                    = this.txtPWD.Text = "";

                this.txtUID.Enabled =
                this.txtPWD.Enabled = false;

            }
            else
            {
                this.txtUID.Enabled =
                this.txtPWD.Enabled = true;
            }
        }

        private void AutoUidPwd(string cbsource)
        {
            string pwds = FileHelper.ReadFromTxt(pwdFilePath);
            string[] strs = pwds.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            string[] pwd;

            if (!string.IsNullOrEmpty(cbsource))
            {
                foreach (string str in strs)
                {
                    if (str.Contains(cbsource))
                    {
                        pwd = str.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                        this.txtUID.Text = pwd[1].ToString();
                        this.txtPWD.Text = TextHelper.StringDecoding(pwd[2].ToString());
                        this.cbsecurity.SelectedIndex = 1;
                        this.cbSource.Text = pwd[0].ToString();
                    }
                }
            }
            else if (strs.Length > 0)
            {
                pwd = strs[strs.Length - 1].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                this.txtUID.Text = pwd[1].ToString();
                this.txtPWD.Text = TextHelper.StringDecoding(pwd[2].ToString());
                this.cbsecurity.SelectedIndex = 1;
                this.cbSource.Text = pwd[0].ToString();
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (MessageBox.Show("确定删除所有保存的密码？", "", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                File.Delete(pwdFilePath);
                MessageBox.Show("删除成功！");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void cbSource_TextChanged(object sender, EventArgs e)
        {
            AutoUidPwd(this.cbSource.Text);
        }

        private void Login_Shown(object sender, EventArgs e)
        {
            this.cbSource.Focus();
        }
    }
}
